<template>
  <el-dialog
    :title="formData.id? '编辑角色': '新增角色'"
    :visible="showDialog"
    width="30%"
    @close="closeFn"
  >
    <el-form ref="form" :model="formData" :rules="rules">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" type="textarea" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="confirmFn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addRole, editRole } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        name: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 确定事件
    async confirmFn() {
      await this.$refs.form.validate()
      if (this.formData.id) {
        // 编辑
        await editRole(this.formData)
        this.$message.success('编辑角色成功')
        this.closeFn()
        this.$emit('updateList')
      } else {
        // 新增
        const res = await addRole(this.formData)
        console.log(54, res)
        this.$message.success('新增角色成功')
        this.closeFn()
        this.$emit('updateList')
      }
    },
    // 取消事件
    closeFn() {
      this.$emit('update:showDialog')
      this.$refs.form.resetFields()
      this.formData = {
        title: '',
        description: ''
      }
    }
  }
}
</script>

<style>

</style>
